<script setup lang="ts">
import { computed, reactive, ref, toRaw } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useEventChannel } from "@/hooks/page";
import { get_identity_type_list_api } from "@/package/activity/api/tour_info";
import {
  create_order_api,
  mini_pay_api,
} from "@/package/activity/api/pin_order";
import { requestPayment } from "@/utils/payment";
import { Storage } from "@/utils/database";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import DetailPriceItem from "./components/detail-price-item.vue";
import FormStepper from "@/components/form/stepper.vue";
import OrderFormCard from "./components/order-form-card.vue";
import IconClose from "@/components/icon/close.vue";
import FormWord from "@/components/form/word.vue";
import OrderSettleBar from "./components/order-settle-bar.vue";
import PopupBottom from "@/components/popup/bottom.vue";

onLoad(() => {
  get_identity_type_list_api().then((resp) => {
    typeList.value = resp.identity_type;
  });
});

const infoData = reactive({
  max_person_num: 1,
  adult_allot_price: "",
  is_include_ticket: 0,
  adult_ticket_price: "",
  child_allot_price: "",
  is_include_child_ticket: 0,
  child_ticket_price: "",
  old_allot_price: "",
  is_include_old_ticket: 0,
  old_ticket_price: "",
});

const formData = reactive({
  adult_num: 1,
  child_num: 0,
  old_num: 0,
  buyer_name: "",
  buyer_phone: "",
  card_type: 1,
  card_no: "",
  identity: [] as any[],
  remark: "",
});

const typeList = ref<any[]>([]);

const travelerClick = (index: number) => {
  if (index === -1) {
    formData.identity.push({
      name: "",
      phone: "",
      card_type: 1,
      card_no: "",
    });
  } else {
    formData.identity.splice(index, 1);
  }
};

const payPrice = computed(() => {
  const adult_allot_price =
    Number(infoData.adult_allot_price) * formData.adult_num;
  const child_allot_price =
    Number(infoData.child_allot_price) * formData.child_num;
  const old_allot_price = Number(infoData.old_allot_price) * formData.old_num;
  return (adult_allot_price + child_allot_price + old_allot_price).toFixed(2);
});

const detailVisible = ref(false);

const btnClick = (type: "detail") => {
  if (type === "detail") {
    detailVisible.value = !detailVisible.value;
  } else {
    Toast.showLoading();
    create_order_api({ pin_id: tempData.id, ...toRaw(formData) })
      .then((resp) => {
        const order_id = resp.order_id;
        return mini_pay_api({ order_id }).then((resp) => {
          Toast.hideLoading();
          requestPayment(
            resp,
            () => {
              Router.redirectTo("/package/activity/pages/dypt/result?type=1");
            },
            () => {
              Storage.setSync("temp-dypt-data", {
                id: order_id,
                price: payPrice.value,
                adult_allot_price: infoData.adult_allot_price,
                is_include_ticket: infoData.is_include_ticket,
                adult_ticket_price: infoData.adult_ticket_price,
                adult_num: formData.adult_num,
                child_allot_price: infoData.child_allot_price,
                is_include_child_ticket: infoData.is_include_child_ticket,
                child_ticket_price: infoData.child_ticket_price,
                child_num: formData.child_num,
                old_allot_price: infoData.old_allot_price,
                is_include_old_ticket: infoData.is_include_old_ticket,
                old_ticket_price: infoData.old_ticket_price,
                old_num: formData.old_num,
              });
              Router.redirectTo(`/package/activity/pages/dypt/result?type=0`);
            }
          );
        });
      })
      .catch(() => Toast.hideLoading());
  }
};

const eventChannel = useEventChannel(() => {
  eventChannel?.once("ev-dypt-data", (resp) => {
    console.log("ev-dypt-data", resp);

    infoData.max_person_num = resp.max_person_num;
    infoData.adult_allot_price = resp.adult_allot_price;
    infoData.is_include_ticket = resp.is_include_ticket;
    infoData.adult_ticket_price = resp.adult_ticket_price;
    infoData.child_allot_price = resp.child_allot_price;
    infoData.is_include_child_ticket = resp.is_include_child_ticket;
    infoData.child_ticket_price = resp.child_ticket_price;
    infoData.old_allot_price = resp.old_allot_price;
    infoData.is_include_old_ticket = resp.is_include_old_ticket;
    infoData.old_ticket_price = resp.old_ticket_price;
    tempData.id = resp.id;
  });
});

const tempData = { id: "" };
</script>

<template>
  <view class="order-info">
    <view class="order-info-title">
      出行人数<text class="order-info-title2">（必填）</text>
    </view>
    <view class="order-info-desc">
      已添加{{
        formData.adult_num + formData.child_num + formData.old_num
      }}位，最多{{ infoData.max_person_num }}位
    </view>
    <view class="order-info-wrapper">
      <DetailPriceItem
        isRequired
        :info="{
          title: '成人',
          price: infoData.adult_allot_price,
          desc: '18周岁(含)~59周岁(含)',
          ticket:
            infoData.is_include_ticket === 1
              ? `含门票￥${infoData.adult_ticket_price}/人`
              : '',
        }"
      >
        <view class="order-info-num">
          <FormStepper
            v-model="formData.adult_num"
            :min="1"
            :max="
              infoData.max_person_num - formData.child_num - formData.old_num
            "
            theme="circle"
          />
        </view>
      </DetailPriceItem>
      <view class="order-info-line"></view>
      <DetailPriceItem
        isRequired
        :info="{
          title: '儿童',
          price: infoData.child_allot_price,
          desc: '17周岁(含)以下',
          ticket:
            infoData.is_include_child_ticket === 1
              ? `含门票￥${infoData.child_ticket_price}/人`
              : '',
        }"
      >
        <view class="order-info-num">
          <FormStepper
            v-model="formData.child_num"
            :min="0"
            :max="
              infoData.max_person_num - formData.adult_num - formData.old_num
            "
            theme="circle"
          />
        </view>
      </DetailPriceItem>
      <view class="order-info-line"></view>
      <DetailPriceItem
        isRequired
        :info="{
          title: '老人',
          price: infoData.old_allot_price,
          desc: '60周岁(含)以上',
          ticket:
            infoData.is_include_old_ticket === 1
              ? `含门票￥${infoData.old_ticket_price}/人`
              : '',
        }"
      >
        <view class="order-info-num">
          <FormStepper
            v-model="formData.old_num"
            :min="0"
            :max="
              infoData.max_person_num - formData.adult_num - formData.child_num
            "
            theme="circle"
          />
        </view>
      </DetailPriceItem>
    </view>
  </view>

  <view class="order-contacts">
    <view class="order-contacts-title">
      联系人信息<text class="order-contacts-title2">（必填）</text>
    </view>
    <OrderFormCard
      :model="formData"
      :typeList="typeList"
      :keyList="['buyer_name', 'buyer_phone', 'card_type', 'card_no']"
    />
  </view>

  <view class="order-traveler">
    <view class="order-traveler-title">联系人信息</view>
    <view
      class="order-traveler-item"
      v-for="(i, d) of formData.identity"
      :key="d"
    >
      <view class="order-traveler-del">
        <IconClose color="#ff4d42" size="20rpx" />
      </view>

      <view class="order-traveler-form">
        <OrderFormCard :model="formData.identity[d]" :typeList="typeList" />
      </view>
    </view>
    <view class="order-traveler-add" @click="travelerClick(-1)">
      <image
        class="order-traveler-add2"
        src="@/package/activity/static/dypt-order-add.png"
      />
      添加客人
    </view>
  </view>

  <view class="order-remark">
    <view class="order-remark-title">备注</view>
    <FormWord
      :modelValue="formData.remark.length"
      :maxlength="200"
      backgroundColor="#f1f1f1"
    >
      <textarea
        class="order-remark-input"
        v-model="formData.remark"
        auto-height
        placeholder="请填写备注信息"
      />
    </FormWord>
  </view>

  <PopupBottom v-model="detailVisible" title="金额明细" :zIndex="8">
    <view class="order-detail">
      <view class="order-detail-item">
        <view style="flex-grow: 1; min-width: 0">
          <DetailPriceItem
            isRequired
            :info="{
              title: '成人',
              price: infoData.adult_allot_price,
              desc: '18周岁(含)~59周岁(含)',
              ticket:
                infoData.is_include_ticket === 1
                  ? `含门票￥${infoData.adult_ticket_price}/人`
                  : '',
            }"
          />
        </view>
        <view class="order-detail-num">
          <text class="order-detail-num2">x</text>{{ formData.adult_num }}
        </view>
      </view>
      <view class="order-detail-line"></view>
      <view class="order-detail-item">
        <view style="flex-grow: 1; min-width: 0">
          <DetailPriceItem
            isRequired
            :info="{
              title: '儿童',
              price: infoData.child_allot_price,
              desc: '17周岁(含)以下',
              ticket:
                infoData.is_include_child_ticket === 1
                  ? `含门票￥${infoData.child_ticket_price}/人`
                  : '',
            }"
          />
        </view>
        <view class="order-detail-num">
          <text class="order-detail-num2">x</text>{{ formData.child_num }}
        </view>
      </view>
      <view class="order-detail-line"></view>
      <view class="order-detail-item">
        <view style="flex-grow: 1; min-width: 0">
          <DetailPriceItem
            isRequired
            :info="{
              title: '老人',
              price: infoData.old_allot_price,
              desc: '60周岁(含)以上',
              ticket:
                infoData.is_include_old_ticket === 1
                  ? `含门票￥${infoData.old_ticket_price}/人`
                  : '',
            }"
          />
        </view>
        <view class="order-detail-num">
          <text class="order-detail-num2">x</text>{{ formData.old_num }}
        </view>
      </view>
    </view>
  </PopupBottom>
  <view class="order-fixed">
    <OrderSettleBar
      title="合计"
      :price="payPrice"
      btnText="去支付"
      @btn-click="btnClick"
    />
  </view>
</template>

<style lang="scss">
page {
  padding-top: 30rpx;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.order-info {
  margin: 0 30rpx 20rpx;

  .order-info-title {
    margin-bottom: 10rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
    font-weight: bold;
  }

  .order-info-title2 {
    font-size: 24rpx;
    color: #ff4d42;
    line-height: 34rpx;
  }

  .order-info-desc {
    margin-bottom: 20rpx;
    font-size: 24rpx;
    color: #1bc76f;
    line-height: 34rpx;
    font-weight: bold;
  }

  .order-info-wrapper {
    padding: 20rpx 20rpx 30rpx;
    border-radius: 20rpx;
    background-color: #ffffff;
  }

  .order-info-num {
    margin-left: 60rpx;
  }

  .order-info-line {
    margin-top: 28rpx;
    margin-bottom: 18rpx;
    border-bottom: 2rpx solid #eeeeee;
  }
}

.order-contacts {
  padding: 30rpx 30rpx 0;
  margin: 0 30rpx 20rpx;
  border-radius: 20rpx;
  background-color: #ffffff;

  .order-contacts-title {
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
    font-weight: bold;
  }

  .order-contacts-title2 {
    font-size: 24rpx;
    color: #ff4d42;
    line-height: 34rpx;
  }
}

.order-traveler {
  padding: 30rpx;
  margin: 0 30rpx 20rpx;
  border-radius: 20rpx;
  background-color: #ffffff;

  .order-traveler-title {
    margin-bottom: 20rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
    font-weight: bold;
  }

  .order-traveler-item {
    position: relative;
    padding-left: 50rpx;
    margin-bottom: 20rpx;
  }

  .order-traveler-del {
    position: absolute;
    left: -10rpx;
    top: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 36rpx;
    height: 36rpx;
    border-radius: 50%;
    border: 2rpx solid #ff4d42;
    transform: translateY(-50%);
  }

  .order-traveler-form {
    padding: 0 30rpx;
    border-radius: 20rpx;
    background-color: #fbfbfb;
  }

  .order-traveler-add {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 174rpx;
    height: 46rpx;
    margin-left: auto;
    font-size: 24rpx;
    color: #ff7900;
    line-height: 32rpx;
    font-weight: bold;
    border-radius: 26rpx;
    border: 2rpx solid #ff7900;
  }

  .order-traveler-add2 {
    width: 32rpx;
    height: 32rpx;
    margin-right: 10rpx;
  }
}

.order-remark {
  margin: 0 30rpx 40rpx;

  .order-remark-title {
    margin-bottom: 20rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
    font-weight: bold;
  }

  .order-remark-input {
    display: block;
    width: 100%;
    min-height: 240rpx;
    padding: 30rpx;
    font-size: 26rpx;
    color: #333333;
    line-height: 36rpx;
    border-radius: 20rpx;
    background-color: transparent;
    box-sizing: border-box;
  }
}

.order-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 104rpx;
  padding-top: 16rpx;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #ffffff;
  z-index: 8;
}

.order-detail {
  padding: 60rpx;
  border-bottom: 122rpx solid #eeeeee;

  .order-detail-item {
    display: flex;
    align-items: flex-start;
  }

  .order-detail-num {
    flex-shrink: 0;
    margin-left: 20rpx;
    margin-top: 8rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
  }

  .order-detail-num2 {
    font-size: 24rpx;
    line-height: 34rpx;
  }

  .order-detail-line {
    margin-top: 28rpx;
    margin-bottom: 18rpx;
    border-bottom: 2rpx solid #eeeeee;
  }
}
</style>